package com.hxx.controller;

import com.hxx.dto.MemberInfo;
import com.hxx.entity.MemberEntity;
import com.hxx.service.MemberService;
import com.hxx.util.JwtUtils;
import com.hxx.util.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Random;

@RestController
public class MemberController {

    @Autowired
    private MemberService memberService;
    private String code;
    /**
     * 登录验证
     */
    @PostMapping("/login")
    public R login(@RequestBody MemberInfo info) {
        //根据手机号码获取信息
        MemberEntity memberEntity = memberService.login(info.getMobile());
        //jwt
        if (memberEntity!=null && code.equals(info.getCode())){
            //jwt令牌
            String token = JwtUtils.createToken(memberEntity.getId(), info.getMobile());
            //把会员及令牌传递到前端
            return R.ok().data("member",memberEntity)
                    .data("token",token);
        }
        return R.error();
    }
    /**
     * 发送验证码
     * @return
     */
    @GetMapping("/sendCode")
    public String sendCode() {
        return MobileCode();
    }

    /**
     * 编写4位验证码
     */
    private String MobileCode(){
        Random random = new Random();
        String code = "";
        for (int i = 0; i < 4; i++) {
            code += random.nextInt(10);
        }
        this.code = code;
        return code;
    }
}



















